package com.cloud.rou.im.protocol.codec;



import com.cloud.rou.im.protocol.serialize.Serializer;
import com.cloud.rou.im.protocol.serialize.SerializerFactory;
import com.cloud.rou.im.protocol.transfer.DataPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * <p></p>the data packet encoder
 * @author GaoShuangWen
 */
public class DataPacketEncoder extends MessageToByteEncoder<DataPacket> {

    @Override
    protected void encode(ChannelHandlerContext ctx, DataPacket msg, ByteBuf out) throws Exception {
        out.writeShort(msg.getHeader().getMagic());
        out.writeShort(msg.getHeader().getVersion());
        byte serializeType = msg.getHeader().getSerializeType();
        Serializer serializer = SerializerFactory.getSerializer(serializeType);
        // 将对象转换为byte
        assert serializer != null;
        byte[] bytes = serializer.serialize(msg.getCmd());
        // 读取消息的长度
        int length = bytes.length;
        // 先将消息长度写入，也就是消息头
        out.writeInt(length);
        out.writeByte(serializeType);
        // 消息体中包含我们要发送的数据
        out.writeBytes(bytes);
    }
}
